package com.evry.spring3sandbox.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.evry.spring3sandbox.domain.Product;

@Repository("productDao")
public class JdbcProductDao extends JdbcDaoSupport implements ProductDao {

	@Autowired
	public JdbcProductDao(DataSource dataSource) {
		setDataSource(dataSource);
	}

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());

	public List<Product> getProductList() {
		logger.info("Getting products!");
		List<Product> products = getJdbcTemplate().query(
				"select id, description, price, name, storagespace, bandwidth, sqldatabase, setupfee from products",
				new ProductMapper());
		return products;
	}

	public void saveProduct(Product prod) {
		logger.info("Saving product: " + prod.getDescription());
		int count = getJdbcTemplate()
				.update("update products set description = ?, price = ?, name = ?, storagespace = ?, bandwidth = ?, sqldatabase = ?, setupfee = ? where id = ?",
						new Object[] {prod.getDescription(), prod.getPrice(), prod.getName(), prod.getStorageSpace(), 
							prod.getBandwidth(), prod.getSqldatabase(), prod.getSetupfee(),prod.getId()});
		logger.info("Rows affected: " + count);
	}

	private static class ProductMapper implements
			ParameterizedRowMapper<Product> {

		public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
			Product prod = new Product();
			prod.setId(rs.getInt("id"));
			prod.setDescription(rs.getString("description"));
			prod.setPrice(new Double(rs.getDouble("price")));
			prod.setName(rs.getString("name"));
			prod.setStorageSpace(rs.getString("storagespace"));
			prod.setBandwidth(rs.getString("bandwidth"));
			prod.setSqldatabase(rs.getString("sqldatabase"));
			prod.setSetupfee(rs.getString("setupfee"));
			return prod;
		}

	}

	@Override
	public Product getProductByID(int id) {
		logger.info("Get product by id.");
		List<Product> products = getJdbcTemplate().query(
				"select id, description, price, name, storagespace, bandwidth, sqldatabase, setupfee from products where id = " + id ,
				new ProductMapper());
		
		return products.get(0);
	}

}